

#import "SearchShopListController.h"
#import "DetailShopViewController.h"
#import "Supplier.h"
#import "SupplierCategory.h"
#import "PublicFunction.h"
#import "UICustomImageView.h"
#import "Constants.h"
#import "AdManager.h"
#import "Ad.h"
#import "FMDBAdManager.h"


@interface SearchShopListController (private)
- (void)refresh;
- (void)stopLoading;
- (void)startLoading;
@end
@implementation SearchShopListController
@synthesize manager;
@synthesize suppliers;
@synthesize currentPage;
@synthesize tableViews; 
@synthesize appDelegate;    
@synthesize _refreshHeaderView;
@synthesize _reloading;
@synthesize scrollView;
@synthesize timeCount;
@synthesize fmdbAdManager;
@synthesize adsCount;
@synthesize conditions;
@synthesize searchType; 
@synthesize address; 
@synthesize isSelling;



//初始化导航栏
-(void)initNav{
    //定义导航栏左侧按钮
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 54, 27)];
    NSString *filePath2=[[NSBundle mainBundle] pathForResource:@"navLeftBtn" ofType:@"png"];
    [leftButton setBackgroundImage:[UIImage imageWithContentsOfFile:filePath2] forState:UIControlStateNormal];
    [leftButton setTitle:@"返 回" forState:UIControlStateNormal]; 
    leftButton.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14]; 
    [leftButton addTarget:self action:@selector(backButtonPressdDelay:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftItem;
}

- (void)backButtonPressdDelay:(id)sender{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    [self performSelector:@selector(backButtonPressd:) withObject:sender afterDelay:0.1];
}

- (void)backButtonPressd:(id)sender{
    //将当前视图推出栈，程序将进入上一视图
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)showHUD{
   MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
	[self.navigationController.view addSubview:HUD];
	HUD.dimBackground = YES;
    HUD.delegate = self;
    [HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
}

- (void)myTask {
    currentPage = 1;
    //直接搜索
    if(searchType==@"0"){
        if([appDelegate status]){
            suppliers= [manager search:conditions pageIndex:1];
//            [fmdbSupplierManager insertSupplierByCategoryId:suppliers supplierCategoryId:appDelegate.supId sPage:@"1"];
        }
//        else{
//            suppliers=[[fmdbSupplierManager getSuppliersByNameOrDishAndPage:conditions sPage:@"1"] retain];
//        }
        if (suppliers == nil) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"没有该类型的商家" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alertView show];
            return;
        }
    }
    //详细搜索
    if(searchType==@"1"){
        if([appDelegate status])
        {
            suppliers = [manager getSupplier:appDelegate.supId pageIndex:currentPage road:address isSelling:isSelling];
        }
        
        if (suppliers.count==0) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"没有该类型的商家" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alertView show];
            return;
        }
        
        
        
//        else
//        {
//            //离线
//            suppliers=[[fmdbSupplierManager getSupplierByCategoryIdAndPageFromLoc:appDelegate.supId sPage:@"1" road:address isSelling:isSelling] retain];
//            NSLog(@"lixianjige%d",[suppliers count]);
//        }
    }
    
    

    //初始化刷新cell
    if([suppliers count]>=5){
        [tableViews reloadData];
        [_refreshHeaderView removeFromSuperview];
        _refreshHeaderView.frame=CGRectMake(0, tableViews.contentSize.height, 320, 250);
        [tableViews addSubview:_refreshHeaderView];
        [_refreshHeaderView refreshLastUpdatedDate];
    }
    else{
        [tableViews reloadData];
        _refreshHeaderView.frame=CGRectMake(0, 600, 320, 250);
    }
}




//显示商家详细信息
- (IBAction)showAd:(id)sender {
    NSInteger textId=[sender tag];
    NSString *adIdForTag = [[NSString alloc] initWithFormat:@"%d", textId];

    Ad *ad=[fmdbAdManager getAdForId:adIdForTag];

    if([[ad type] isEqualToString:@"网页广告"]){
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:ad.value]];
    }
    if([[ad type] isEqualToString:@"推荐商家"]){
        //创建新的试图并将试图推入栈中
        DetailShopViewController *detailShopViewController = [[DetailShopViewController alloc]init];
        NSMutableDictionary *dictionary2 = [NSMutableDictionary dictionaryWithCapacity :1];
        [dictionary2 setObject:ad.value forKey:@"supId"];
        [detailShopViewController setRecieveDictionary:dictionary2];
        [self.navigationController pushViewController: detailShopViewController animated:YES];
    }
}

//设置时间
-(void)scrollTimer{
    timeCount ++;
    if (timeCount == adsCount) {
        timeCount = 0;
    }
    [scrollView scrollRectToVisible:CGRectMake(timeCount * 320.0, 65.0, 320.0, 60.0) animated:YES];
}

//初始化广告
-(void)initAd
{
    
    AdManager *adManager=[[AdManager alloc]init];
    fmdbAdManager=[[FMDBAdManager alloc] init];
    NSArray *ads=nil;
    if([appDelegate status]){
        ads=[adManager getSupplierByPosition:@"首页"];
        //插入到本地
        [fmdbAdManager insertAd:ads position:@"首页"];
        
    }
    //    else{
    //        ads=[fmdbAdManager getAdForPosition:@"首页"];
    //    } 
    //广告图大小320*60
    // Create the scroll view and set its content size and delegate
    //小图
    //    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f, 371.0f, 320.0f, 120.0f)];
    //大图
    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f, -65.0f, 320.0f, 120.0f)];
    scrollView.contentSize = CGSizeMake([ads count] * 320.0f, scrollView.frame.size.height);//3张图片
    scrollView.pagingEnabled = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.delegate = self;
    adsCount=[ads count];
    //load the scroll view
    for (int i = 0; i < [ads count]; i++) {
        
        UICustomImageView *adImageView = [[UICustomImageView alloc] initWithFrame:CGRectMake(i * 320.0f,  60.0f, 320.0f, 60.0f)];
        [adImageView setContentMode:UIViewContentModeScaleAspectFit];
        [adImageView setUserInteractionEnabled:YES];
        adImageView.tag=900+i;
        [adImageView setImage:nil];
        [adImageView setImageURL:((Ad *)[ads objectAtIndex:i]).imgUrl];
        
        UIButton *adImgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        adImgBtn.frame=CGRectMake(i * 320.0f,  60.0f, 320.0f, 60.0f);
        [adImgBtn setTag:((Ad *)[ads objectAtIndex:i]).adId];
        //        adImgBtn.backgroundColor = [UIColor clearColor];
        [adImgBtn addTarget:self action:@selector(showAd:) forControlEvents:UIControlEventTouchUpInside];
        
        [scrollView addSubview:adImageView];
        [scrollView addSubview:adImgBtn];
        
    }

    [self.view addSubview:scrollView];
    timeCount = 0;
    //    [ads release];
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(scrollTimer) userInfo:nil repeats:YES];
}

- (void)viewDidLoad { 
    [super viewDidLoad];
    
    //添加手势
    //后退
    UISwipeGestureRecognizer *recognizer; 
    recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [[self view] addGestureRecognizer:recognizer];
    
    //设置视图title
    self.title=@"商家列表";
    //初始化导航栏
    [self initNav];
    //初始化商家管理类
    manager = [[SupplierManager alloc] init];
//    fmdbSupplierManager=[[FMDBSupplierManager alloc]init];
    appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    
    tableViews=[[UITableView alloc] initWithFrame:CGRectMake(0, 55, 320, 312)];  
    tableViews.backgroundColor=[UIColor whiteColor];  
    //添加到view窗体上  
    [self.view addSubview:tableViews];  
    tableViews.delegate=self;  
    tableViews.dataSource=self; 
    tableViews.contentSize =CGSizeMake(320, [suppliers count]*64);
    //减慢tableview的滚动速度，正常值为1.f
    tableViews.decelerationRate=0.5f;
    
    _refreshHeaderView=[[EGORefreshTableHeaderView alloc] init];
    _refreshHeaderView.delegate=self;
    
    [self initAd];
    [self showHUD];
}

- (void)viewWillAppear:(BOOL)animated{
    //设置显示导航栏
    self.navigationController.navigationBarHidden = NO; 
}

//手势
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
    //后退
    if(recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

/**************************/ 
/*       商家列表视图       */
/*************************/

//返回表试图分区行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [suppliers count];
}

//设置表试图每行显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger index=indexPath.row;
    Supplier *supplier=[suppliers objectAtIndex:index];
    static NSString *CellIdentifier = @"CustomCell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    
	if(cell == nil) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    } 
    cell.opaque=YES;
    UICustomImageView *imageView = (UICustomImageView *)[cell.contentView viewWithTag:100];
    if (imageView == nil) {     
        imageView = [[UICustomImageView alloc] initWithFrame:CGRectMake(8, 2, 60, 60)];
        imageView.opaque=YES;
        [imageView setContentMode:UIViewContentModeScaleAspectFit];
        [imageView setUserInteractionEnabled:NO];
        [imageView setTag:100];
        [cell.contentView addSubview:imageView];
    }
    [imageView setImage:nil];
    [imageView setImageURL:supplier.imgUrl];
    
    UILabel *shopNameLabel = (UILabel *)[cell.contentView viewWithTag:200];
    if (shopNameLabel == nil) {
        //标题2
        shopNameLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16];
        shopNameLabel.opaque=YES;
        shopNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, 5, 220, 16)];
        //自定义颜色
        [shopNameLabel setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
        [shopNameLabel setText:supplier.supplierName];
        shopNameLabel.tag = 200;
        [cell.contentView addSubview:shopNameLabel];
    }
    [shopNameLabel setText:supplier.supplierName];
    
    UILabel *shopTypeLable=(UILabel *)[cell.contentView viewWithTag:202];
    if (shopTypeLable == nil) {
        shopTypeLable = [[UILabel alloc] initWithFrame:CGRectMake(80, 30, 160, 12)];
        shopTypeLable.opaque=YES;
        shopTypeLable.font=[UIFont fontWithName:@"Helvetica" size:12];
        shopTypeLable.tag = 202;
        [cell.contentView addSubview:shopTypeLable];
    }
    //    NSString *supplierCategoryName = [NSString stringWithFormat:@"【%@】",supplier.supplierCategoryName];
    NSString *supplierCategoryName = [[NSString alloc] initWithFormat:@"【%@】",supplier.supplierCategoryName];
    [shopTypeLable setText:supplierCategoryName];
    
    UILabel *shopAvgPriceLable=(UILabel *)[cell.contentView viewWithTag:203];
    if (shopAvgPriceLable == nil) {
        shopAvgPriceLable = [[UILabel alloc] initWithFrame:CGRectMake(165, 30, 100, 12)];
        shopAvgPriceLable.opaque=YES;
        shopAvgPriceLable.font=[UIFont fontWithName:@"Helvetica" size:12];
        //自定义颜色
        [shopAvgPriceLable setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
        [shopAvgPriceLable setBackgroundColor:[UIColor clearColor]];
        shopAvgPriceLable.tag = 203;
        [cell.contentView addSubview:shopAvgPriceLable];
    }
    NSString *avgPrice=[[NSString alloc]initWithFormat:@"人均: %.2f",supplier.avgPrice];
    [shopAvgPriceLable setText:avgPrice];
    
    UILabel *shopAddressLabel = (UILabel *)[cell.contentView viewWithTag:201];
    if (shopAddressLabel == nil) {
        shopAddressLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, 48, 160, 12)];
        shopAddressLabel.opaque=YES;
        shopAddressLabel.font=[UIFont fontWithName:@"Helvetica" size:12];
        [shopAddressLabel setBackgroundColor:[UIColor clearColor]];
        shopAddressLabel.tag = 201;
        [cell.contentView addSubview:shopAddressLabel];
    }
    NSString *tempAddress=[[NSString alloc]initWithFormat:@"地址: %@",supplier.address]; 
    [shopAddressLabel setText:tempAddress];
    
    UIButton *phoneButton = (UIButton *)[cell.contentView viewWithTag:300];
    if (phoneButton == nil) 
    {
        phoneButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
        phoneButton.opaque=YES;
        [phoneButton setFrame:CGRectMake(240, 27, 30, 30)];
        
        NSString *filePath=[[NSBundle mainBundle] pathForResource:@"phoneImg" ofType:@"png"];
        UIImage *image = [UIImage imageWithContentsOfFile:filePath]; 
        [phoneButton setBackgroundImage:image forState:UIControlStateNormal]; 
        phoneButton.tag = 300;
        [phoneButton addTarget:self action:@selector(callAction:event:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:phoneButton];
        //点击拨号按钮直接拨号
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    cell.tag = supplier.supplierId;
    return cell;
}

//定义点击拨号按钮时的操作 
- (void)callAction:(id)sender event:(id)event{ 
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    NSSet *touches = [event allTouches]; 
    UITouch *touch = [touches anyObject]; 
    CGPoint currentTouchPosition = [touch locationInView:tableViews]; 
    NSIndexPath *indexPath = [tableViews indexPathForRowAtPoint: currentTouchPosition]; 
    if (indexPath == nil) { 
        return; 
    } 
    NSUInteger  row = [indexPath row]; 
    Supplier *rowData = [suppliers objectAtIndex:row]; 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"拨打电话" message:@"请选择要拨打的号码" delegate:self cancelButtonTitle:@"取  消" otherButtonTitles:nil];
    if(rowData.phone.length != 0){
        [alert addButtonWithTitle:rowData.phone];
    }
    if(rowData.phone2.length != 0){
        [alert addButtonWithTitle:rowData.phone2];
    }
    if(rowData.telephone.length != 0){
        [alert addButtonWithTitle:rowData.telephone];
    }
    if(rowData.telephone2.length != 0){
        [alert addButtonWithTitle:rowData.telephone2];
    } 
    alert.tag = 1;
	[alert show];
}

//根据被点击按钮的索引处理点击事件  
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {  
    //tag为1时为点击拨号按钮时弹出的对话框
    if(alertView.tag == 1){
        NSString *number = [alertView buttonTitleAtIndex:buttonIndex];
        //phoneNumber为号码字符串 
        NSString *phoneNumber = [[NSString alloc] initWithFormat:@"tel://%@",number]; 
        //拨号 
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]]; 
    }
}

//选中Cell响应事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//选中后的反显颜色即刻消失
    NSString *supplierId = [[NSString alloc] initWithFormat:@"%d",[tableView cellForRowAtIndexPath:indexPath].tag];
    Supplier *supplierDetail= [manager getSupplierDetailById:supplierId];
//    if([appDelegate status]){
//        //联网
//        supplierDetail = [manager getSupplierDetailById:supplierId];
//    }
//    else{
//        //离线
//        supplierDetail=[fmdbSupplierManager getSupplierDetailByIdFromLoc:supplierId];
//    }
    //创建新的试图并将试图推入栈中
    DetailShopViewController *detailShopViewController = [[DetailShopViewController alloc]init];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity :2];
    [dictionary setObject:supplierId forKey:@"supId"];
    [dictionary setObject:supplierDetail forKey:@"Supplier"];
    [detailShopViewController setRecieveDictionary:dictionary];  
    [self.navigationController pushViewController: detailShopViewController animated:YES];
}

//设置表试图行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath   
{
    return 64;
}

//新刷新控件
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)addObject{
    currentPage++;
    NSArray *newSuppliers=nil;
//    NSString *currentPageString=[NSString stringWithFormat: @"%d", currentPage];        
    //直接搜索
    if(searchType==@"0")
    {
        if([appDelegate status])
        {
            newSuppliers= [manager search:conditions pageIndex:currentPage];
//            [fmdbSupplierManager insertSupplierByCategoryId:suppliers supplierCategoryId:appDelegate.supId sPage:currentPageString];
        }
//        else
//        {
//            //离线
//            newSuppliers=[fmdbSupplierManager getSuppliersByNameOrDishAndPage:conditions sPage:currentPageString];
//        }
    }
    //详细搜索
    if(searchType==@"1")
    {
        if([appDelegate status])
        {
            newSuppliers = [manager getSupplier:appDelegate.supId pageIndex:currentPage road:address isSelling:isSelling];
        }
//        else
//        {
//            //离线
//            newSuppliers=[fmdbSupplierManager getSupplierByCategoryIdAndPageFromLoc:appDelegate.supId sPage:currentPageString road:address isSelling:isSelling];
//        }
    }
    if (newSuppliers != nil) {
        suppliers = [suppliers arrayByAddingObjectsFromArray:newSuppliers];
    }
	//回到主线程跟新界面
	[self performSelectorOnMainThread:@selector(dosomething) withObject:nil waitUntilDone:YES];
}

//此方法是开始读取数据
- (void)reloadTableViewDataSource{
        tableViews.scrollEnabled=NO;
    //设置tabbar不能点击
    appDelegate.rootController.tabBar.userInteractionEnabled=NO;
	_reloading = YES;
	//打开线程，读取网络图片
	[NSThread detachNewThreadSelector:@selector(addObject) toTarget:self withObject:nil];
}

//更改refreshHeaderView位置
-(void)dosomething
{
	int count=[suppliers count];
	if(64*count>320)
	{
		tableViews.contentSize=CGSizeMake(320, 64*count);
		_refreshHeaderView.frame=CGRectMake(0, tableViews.contentSize.height, 320, 250);
	}

    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0];
}

//此方法是结束读取数据
- (void)doneLoadingTableViewData{
        tableViews.scrollEnabled=YES;
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    //设置tabbar能点击
    appDelegate.rootController.tabBar.userInteractionEnabled=YES;
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:tableViews];
        	[tableViews reloadData];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	
	[_refreshHeaderView egoRefreshScrollViewDidScroll:tableViews];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:tableViews];
}

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	[self reloadTableViewDataSource];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	return _reloading;
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	return [NSDate date];
}

/************************/ 
/*     索搜类型选取器      */
/************************/
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewDidUnload{
self.manager=nil;
self.suppliers=nil;
self.tableViews=nil; 
self.appDelegate=nil;    
self._refreshHeaderView=nil;
self.scrollView=nil;
self.fmdbAdManager=nil;
self.conditions=nil;
self.searchType=nil; 
self.address=nil; 
self.isSelling=nil;
    [super viewDidUnload];
}

//- (void)dealloc {
//
//}
@end
